package com.lin.eat.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.eat.entry.*;
import com.lin.eat.dao.CustomerMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {

    public CustomerMapper customerMapper;

    public TokenInterceptor(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        ServerResponse serverResponse = null;

        try {

            //是不是映射到方法上
            boolean isHandlerMethod = handler instanceof HandlerMethod;
            if(!isHandlerMethod){
                out = response.getWriter();
                serverResponse = new ServerResponse(404, "页面不存在", false,null);
                out.print(new ObjectMapper().writeValueAsString(serverResponse));
                out.flush();
                System.out.println("拦截");
                return false;
            }

            String token = request.getHeader("token");
            Customer customer = customerMapper.findCustomerByToken(token);
            Boolean flag = null;
            if(token == null || token.equals("null") || customer == null){
                flag = false;
                out = response.getWriter();
                serverResponse = new ServerResponse(201, "失败", false,null);
                out.print(new ObjectMapper().writeValueAsString(serverResponse));
                out.flush();
            }else {
                flag = true;
            }

            System.out.println("拦截");
            return flag;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("通过了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
